const router = require('express').Router();
const cateModel = require('../model/cate');
// 分类列表页
router.get('/cateList', async (req,res) => {
  // 解构赋值默认值
  let { current = 1, pageSize = 2 } = req.query;
  current = parseInt(current);
  pageSize = parseInt(pageSize);
  const cates = await cateModel.find().limit(pageSize).skip((current-1)*pageSize).sort({
    _id: -1
  })
  const counts = await cateModel.count();
  res.render('cateList', {
    cates,
    counts,
    current
  })
})
// 增加分类页
router.get('/cateAdd', async (req,res) => {
  // 获取所有的分类
  const cates = await cateModel.find().sort({_id: -1});
  res.render('cateAdd', {
    cates
  })
})
// 增加分类
router.post('/cateAdd', (req,res)=>{
  
  cateModel.insertMany(req.body).then(ret => {
    res.send({
      code: 0,
      msg: '增加成功'
    })
  }).catch(err=>{
    res.send({
      code: -1,
      msg: '增加失败'
    })
  })
})
// 更新分类页
router.get('/cateUpdate', async (req,res) => {
  const { id } = req.query;
  // 根据id获取 这条分类的数据
  const cate = await cateModel.findOne({
    _id: id
  });
  // 获取所有分类
  const cates = await cateModel.find().sort({_id: -1});
  res.render('cateUpdate', {
    cate,
    cates
  })
})
// 更新分类
router.post('/cateUpdate', (req,res) => {
  cateModel.updateOne({
    _id: req.body.id
  },req.body).then(ret=>{
    res.send({
      code: 0,
      msg: '修改成功'
    })
  }).catch(err=>{
    res.send({
      code: -1,
      msg: '修改失败'
    })
  })
})

router.post('/delCate', (req,res)=> {
  const {id} = req.body;
  cateModel.remove({
    _id: id
  }).then(ret=>{
    res.send({
      code: 0,
      msg: '删除成功'
    })
  }).catch(err=>{
    res.send({
      code: -1,
      msg: '删除失败'
    })
  })
})


module.exports = router;